package com.dragon.controller;

import com.dragon.AppSettingFactory;
import com.riversoft.weixin.common.oauth2.AccessToken;
import com.riversoft.weixin.common.oauth2.OpenUser;
import com.riversoft.weixin.mp.oauth2.MpOAuth2s;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/demo")
public class WechatDemoController {

    @Autowired
    AppSettingFactory appSettingFactory;

    @Value("${wechat.oatuh.redirectUrl}")
    String wechatRedirectUrl;

    @Autowired
    Environment env;

    @RequestMapping("/login")
    public String login(){
        MpOAuth2s oatuh = MpOAuth2s.with(appSettingFactory.getAppSetting());
        String url=oatuh.
                authenticationUrl(this.wechatRedirectUrl,"snsapi_userinfo");
        return "redirect:"+url;
    }

    @RequestMapping("/callback")
    @ResponseBody
    public OpenUser callback(@RequestParam(name="code") String code){
        MpOAuth2s oatuh = MpOAuth2s.with(appSettingFactory.getAppSetting());
        AccessToken accessToken = oatuh.getAccessToken(code);
        OpenUser wechatUser = oatuh.userInfo(accessToken.getAccessToken(), accessToken.getOpenId());

        String profile=env.getProperty("spring.profiles.active","dev");
        if(profile.equals("dev")) {
            wechatUser.setUnionId("testUnionId");
        }
        return wechatUser;
    }

}
